#include "keyboard.h"

KEYStruct key;                                   

KEYStruct* GetKeyStruct(void)                 
{
	
    return &key;             
	
}

//清除列
static void ClsC(void)
{
	P44 = 0;
	P42 = 0;
	P32 = 1;
	P33 = 1;
}

//清除行
static void ClsR(void)
{
	P32 = 0;
	P33 = 0;
	P44 = 1;
	P42 = 1;		
}

//
void ScanKeyboard(void)
{
	static unsigned char col = 0;
	switch(key.status)
    {
		case 0:
			ClsR();
			if((P44 == 0)||(P42 == 0)){
				key.status = 1;
			}
			break;
		case 1:
			ClsR();
			if(P44 == 0){
				col = 1;
				key.status = 2;
			}else if(P42 == 0){
				col = 2;
				key.status = 2;
			}
			break;
		case 2:
			ClsC();
			if(P32 == 0){
				key.value = col + 2;
				key.status = 3;
			}else if(P33 == 0){
				key.value = col;
				key.status = 3;
			}else{
				key.status = 0;	//抖动
			}
			break;
		case 3:
			ClsC();	
			if((P32 == 1)&&(P33 == 1)){
				key.status = 0;
			}
			break;
	}
}

void InitKeyStruct(void)
{
    key.pFun = ScanKeyboard;
    key.value = 0xFF;
    key.status = 0;
}

//状态复位
void combkey(void)
{
	unsigned char tmp = 0;
	static unsigned int count = 0;
	
	if(P44) tmp |= 8;
	if(P42) tmp |= 4;
	if(P33) tmp |= 2;
	if(P32) tmp |= 1;
	
	P32 = 1;
	P33 = 1;
	P44 = 1;
	P42 = 0;
	if ((P32 == 0) && (P33 == 0)){
		if(++count == 40000){
			IAP_CONTR = 0x20;
		}
	}else{
		count = 0;
	}
	P44 = (tmp >> 3)&1;
	P42 = (tmp >> 2)&1;
	P33 = (tmp >> 1)&1;
	P32 = tmp & 1;
}
